<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/16 21:15
 * @version
 */
namespace App\Console\Commands;

use App\MobileRecharge;
use App\Models\MobileRechargeOrder;
use App\Models\MobileRechargeOrderDetail;
use App\Models\MobileRechargeTask;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SyncMobileRechargeStatusCommand extends Command
{
    protected $signature = 'mobile:sync:status';

    protected $description = 'Sync Mobile Recharge Status';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $tasks = MobileRechargeTask::whereIn('status', [1,2])
            ->where('pay_at', '>', Carbon::now()->subMonths(6)->toDateTimeString())
            ->lockForUpdate()->take(10)->get();
        $tasks = json_decode(json_encode($tasks),true);
        foreach ($tasks as $task) {
            $res = MobileRecharge::syncOrderStatus($task['sn']);
            if($res===true){
                DB::beginTransaction();
                try {
                    //更新任务状态
                    (new MobileRechargeTask())->query()->where('id', $task['id'])->update(['status' => 9]);
                    //更新订单详情状态
                    (new MobileRechargeOrderDetail())->query()->where('id', $task['recharge_order_detail_id'])->update(['result_status' => 1]);
                    $detail = (new MobileRechargeOrderDetail())->query()->where('id', $task['recharge_order_detail_id'])->first();
                    if ($detail) {
                        if ($detail->current_month == $detail->total_month) {
                            //更新订单状态
                            (new MobileRechargeOrder())->query()->where('id', $detail->recharge_order_id)->update(['status' => 3]);
                        }
                    }else{
                        (new MobileRechargeOrder())->query()->where('id', $task['recharge_order_id'])->update(['status' => 3]);
                    }
                    DB::commit();
                    //TODO:发送通知
                }catch(\Exception $e){
                    Log::error($e->getMessage());
                    DB::rollBack();
                }
            }
            $this->line('mobile crontab:' . $task['id']);
        }
    }

}